<template>
      <!--使用抽屉模式 把所有图片加载到抽屉窗体中-->
  <!-- <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
      open
    </el-button> -->

    <!-- 使用avatar头像组件实现头像上传模式 -->
    <!-- 把图像改成头像模式 -->
  <el-avatar shape="cover" :size="100" :src="imgurl" @click="drawer = true">
    <img src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png">
  </el-avatar>
   <!--使用抽屉模式 把所有图片加载到抽屉窗体中-->
  <el-drawer v-model="drawer" title="我的图库" direction="ttb" size="40%">
    <el-upload v-model:file-list="fileList" list-type="picture-card" :auto-upload="false" :on-change="onChange">
      <el-icon>
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <!--@click="getImgurl(file.url)" 实现点击图片给头像赋值-->
            <span class="el-upload-list__item-preview" @click="getImgurl(file.url)">
              <el-icon><zoom-in /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
  </el-drawer>
</template>
<script setup>
import { getimg, upload } from "@/api/UploadApi"
import { ref , onMounted } from "vue"
const fileList = ref([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  }
])
const drawer = ref(false)
const onChange = (uploadFile, uploadFiles) => {
  console.log(uploadFile);
  let name = uploadFile.name
  console.log(name);
  let file = uploadFile.raw
  console.log(file);
  //读取file  FileReader 是一个异步读取存储在用户计算机上的文件
  let reader = new FileReader()
  // 开始读取指定的file中的内容，一旦完成，
  //result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容
  reader.readAsDataURL(file)
  //使用onload读取提取base64
  reader.onload = () => { 
    //打印base64码 结果
    console.log(reader.result);
    CallUploadApi(name, reader.result)
  }
}

const imgurl=ref()
const getImgurl = (imageUrl) => { 
  console.log("imageUrl===", imageUrl);
  imgurl.value = imageUrl //赋值头像
  drawer.value = false //赋值后关闭窗口
  
}


onMounted(() => { 
  CallUImgList()
})
const CallUploadApi = (name,base64) => { 
  upload({name:name,base64:base64}).then(res => { 
    console.log(res);
    //上传完列表进行刷新
    CallUImgList()
  })
}
const CallUImgList = () => { 
  getimg().then(res => { 
    console.log(res.data);
    fileList.value=res.data
  })
}

</script>
